package com.ternnetwork.batch.reader;

import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.LineMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.batch.item.file.transform.LineTokenizer;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;

import com.ternnetwork.batch.model.TestUser;



/**
 * 文本文件读取器
 * @author xuwenfeng
 *
 */
@Component("testUserFlatFileItemReader")
public class TestUserFlatFileItemReader extends FlatFileItemReader<TestUser> {
	
	public TestUserFlatFileItemReader(){
		createReader();
	}
	
	private void createReader(){
		
		
		this.setLinesToSkip(1);
		this.setLineMapper(userLineMapper());
	}
	
	private LineMapper<TestUser> userLineMapper(){
		DefaultLineMapper<TestUser> lineMapper = new DefaultLineMapper<>();
		lineMapper.setLineTokenizer(userLineTokenizer());
		lineMapper.setFieldSetMapper(new UserFieldStepMapper());
		lineMapper.afterPropertiesSet(); 
		return lineMapper;
	}
	
    private LineTokenizer userLineTokenizer(){
        DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
        tokenizer.setNames(new String[]{"ID", "NAME", "AGE"});
        return tokenizer;
    }
    
    private static class UserFieldStepMapper implements FieldSetMapper<TestUser>{
		@Override
		public TestUser mapFieldSet(FieldSet fieldSet) throws BindException {
            return new TestUser(fieldSet.readString("ID"), 
                            fieldSet.readString("NAME"), 
                            fieldSet.readString("AGE"));
		}

    }

    
}
